package rootdb

import (
	"errors"
	"time"

	"gitee.com/xiaoyutab/xgotool/xgodb"
	"gitee.com/xiaoyutab/xgotool/xgodb/xgodbconfig"
	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
)

// 获取root数据库连接
func Connect() (*gorm.DB, error) {
	if _default.RootPath == "" {
		return nil, errors.New("数据库未找到")
	}
	if _default.DB != nil {
		return _default.DB, nil
	}
	db, err := gorm.Open(sqlite.Open(_default.RootPath))
	if err != nil {
		return nil, err
	}
	_default.DB = db
	_default.DB.AutoMigrate(&Dervice{}, &DerviceMac{}, &File{})
	// 配置项依赖
	xgodb.Regedit(&xgodb.Config{
		DB: db,
	})
	reg_config()
	return _default.DB, nil
}

// 配置项注册
func reg_config() {
	// 分组注册
	xgodbconfig.GroupInserts([]xgodbconfig.ConfigureGroup{
		{Id: 1, Fid: 0, NameGroup: "RUN", NameGroupCn: "运行配置"},
		{Id: 2, Fid: 0, NameGroup: "SDK", NameGroupCn: "三方配置"},

		{Id: 101, NameGroup: "RUN", Fid: 1, NameGroupCn: "基础运行配置"},
		{Id: 102, NameGroup: "SDK_MAIL", Fid: 2, NameGroupCn: "备份邮箱配置"},
		{Id: 103, NameGroup: "SDK_OSS_ALI", Fid: 2, NameGroupCn: "阿里OSS配置"},
		{Id: 104, NameGroup: "SDK_OSS_TENCENT", Fid: 2, NameGroupCn: "腾讯OSS配置"},
		{Id: 105, NameGroup: "SDK_OSS_HUAWEI", Fid: 2, NameGroupCn: "华为OSS配置"},
		{Id: 106, NameGroup: "RUN_TAR", Fid: 1, NameGroupCn: "文件压缩配置"},
	})
	// 具体配置项注册
	xgodbconfig.InsertsOrContinue([]xgodbconfig.Configure{
		{NameKey: "RUN_FILE_NAME", NameCn: "文件名前缀", NameGroup: "RUN", Types: "string", Desc: "文件名信息，后面跟年月日时分秒后缀", ValueString: "logs_"},
		{NameKey: "RUN_FILE_PATH", NameCn: "文件存放位置", NameGroup: "RUN", Types: "string", Desc: "文件存放位置，目录", ValueString: "/tmp/"},
		{NameKey: "RUN_FILE_SIZE", NameCn: "文件拆分大小", NameGroup: "RUN", Types: "int", Desc: "文件拆分大小，单位：B，1MB = 1024KB = 1048576B", ValueInt: 104857600},
		{NameKey: "RUN_LOG_INFO_SEARCH", NameCn: "日志详情片", NameGroup: "RUN", Types: "int", Desc: "查看日志详情时的时间片，即该详情的前后多长时间，单位：秒", ValueInt: 60},
		{NameKey: "RUN_LOG_MIN_ID", NameCn: "当前日志系统中的最小ID", NameGroup: "RUN", Types: "int", Desc: "当前系统中的最小ID", ValueInt: time.Now().UnixNano()},
		{NameKey: "RUN_TAR_DELETE", NameCn: "删除原日志", NameGroup: "RUN_TAR", Types: "bool", Desc: "压缩日志后是否自动删除原日志", ValueBool: 1},
		{NameKey: "RUN_TAR_DAYS", NameCn: "压缩旧日志", NameGroup: "RUN_TAR", Types: "int", Desc: "自动压缩XXX天以前的日志，单位：天，备份会有误差，建议留有足够的存储空间。0-不自动压缩", ValueInt: 0},
	})
}
